package com.dcxs.shop.module.user.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dcxs.shop.common.annotation.UnAuthRequest;
import com.dcxs.shop.common.utils.*;
import com.dcxs.shop.module.order.entity.JsProductOrder;
import com.dcxs.shop.module.order.service.IJsProductOrderService;
import com.dcxs.shop.module.user.entity.JsUsr;
import com.dcxs.shop.module.user.form.GetCodeForm;
import com.dcxs.shop.module.user.form.LoginForm;
import com.dcxs.shop.module.user.form.SendMessageForm;
import com.dcxs.shop.module.user.service.IJsUsrService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-02-22
 */
@RestController
@RequestMapping("/user/js-usr")
@Api("用户接口")
public class JsUsrController {

    @Autowired
    private IJsUsrService usrService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private SendMessageUtils sendMessageUtils;

    @Autowired
    private RedisUtils redisUtils;

    //验证码模板ID
    @Value("${dcxs.message.verTemplateId}")
    public String verTemplateId;

    private final WxMpService wxService;

    @Autowired
    private IJsProductOrderService orderService;

    public JsUsrController(WxMpService wxService) {
        this.wxService = wxService;
    }

    @PostMapping("/login/getCode")
    @ApiOperation("获取验证码")
    @UnAuthRequest
    public R getCode(@RequestBody GetCodeForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);
        String code = RandomUtil.randomNumbers(6);
        JSONObject param = JSONUtil.createObj();
        param.put("code",code);
        SendMessageForm sendMessageForm = new SendMessageForm();
        sendMessageForm.setMobile(form.getMobile());
        sendMessageForm.setTemplateCode(verTemplateId);
        sendMessageForm.setTemplateParam(param.toString());
        String res = sendMessageUtils.send(sendMessageForm);
        redisUtils.set(form.getMobile(),code,300);
        if(StringUtils.isNotBlank(res)&&"OK".equals(JSONUtil.parseObj(res).get("Code"))){
            return  R.ok();
        }else {
            return R.error();
        }
    }


    @PostMapping("/login")
    @ApiOperation("登录")
    @UnAuthRequest
    public R login(@RequestBody LoginForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form);
        //查询是否存在此用户的手机号
        Integer integer = usrService.count(new QueryWrapper<JsUsr>().eq("phone", form.getMobile()));
        if (integer <= 0) {
            //保存用户手机号
            JsUsr jsUsr = new JsUsr();
            jsUsr.setBalance(new BigDecimal("0"));
            jsUsr.setPhone(form.getMobile());
            jsUsr.setNickname(form.getMobile());
            jsUsr.setBalance(new BigDecimal("0"));
            jsUsr.setCreateDate(LocalDateTime.now());
            usrService.save(jsUsr);
        }
        String code = redisUtils.get(form.getMobile());
        if (form.getCode().equals(code)) {
            JsUsr usr = usrService.getOne(new QueryWrapper<JsUsr>().eq("phone", form.getMobile()));
            if (null != usr) {
                return R.ok().put("token", jwtUtils.generateToken(Long.valueOf(form.getMobile()))).put("name", usr.getNickname()).put("usrId",usr.getId());
            }
        } else {
            return R.error("验证码错误");
        }
        return R.error();
    }



    @PostMapping("/addPage")
    @ApiOperation("微信授权登录")
    @UnAuthRequest
    public R addPage(@RequestParam String code) {
        try {
            WxMpOAuth2AccessToken accessToken = wxService.oauth2getAccessToken(code);
            WxMpUser user = wxService.oauth2getUserInfo(accessToken, null);
            //查询这个openId是否已经被手机号绑定
            List<JsUsr> usrs = usrService.list(new QueryWrapper<JsUsr>().eq("open_id",user.getOpenId()));
            if(CollectionUtil.isNotEmpty(usrs)){
                return R.ok().put("token",jwtUtils.generateToken(Long.valueOf(usrs.get(0).getPhone()))).put("name",usrs.get(0).getNickname()).put("usrId",usrs.get(0).getId());
            }else {
                return new R().put("openId",user.getOpenId());
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            return  R.error();
        }
    }


    @PostMapping("/bindPhone")
    @ApiOperation("openId绑定手机号")
    @UnAuthRequest
    public R bindPhone(@RequestBody JsUsr usr) {
           //查询这个手机号存在否
        String code = redisUtils.get(usr.getPhone());
        if (usr.getCode().equals(code)) {
            JsUsr jsUsr = usrService.getOne(new QueryWrapper<JsUsr>().eq("phone",usr.getPhone()));
            if(null==jsUsr){
                JsUsr usr1 = new JsUsr();
                usr1.setBalance(new BigDecimal("0"));
                usr1.setNickname(usr.getPhone());
                usr1.setPhone(usr.getPhone());
                usr1.setCreateDate(LocalDateTime.now());
                usr1.setOpenId(usr.getOpenId());
                usrService.save(usr1);
                return R.ok().put("token",jwtUtils.generateToken(Long.valueOf(usr1.getPhone()))).put("name",usr1.getNickname()).put("usrId",usr1.getId());
            }else {
                jsUsr.setNickname(usr.getPhone());
                jsUsr.setOpenId(usr.getOpenId());
                usrService.updateById(jsUsr);
                return R.ok().put("token",jwtUtils.generateToken(Long.valueOf(jsUsr.getPhone()))).put("name",jsUsr.getNickname()).put("usrId",jsUsr.getId());
            }

        } else {
            return R.error("验证码错误");
        }
    }

    @RequestMapping("/useJsSdk")
    @UnAuthRequest
    public R useJsSdk(@RequestParam String url){
        try {
            WxJsapiSignature wxJsapiSignature = wxService.createJsapiSignature( java.net.URLDecoder.decode(url, "UTF-8"));
            Console.log(java.net.URLDecoder.decode(url, "UTF-8"));
            Console.log(wxService.getJsapiTicket());
            R r = new R();
            r.put("data",wxJsapiSignature);
            return r;
        }catch (WxErrorException e){
            e.printStackTrace();
            return R.error("系统错误");
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
            return R.error("系统错误");
        }
    }

    @RequestMapping("/getOrderCount")
    public R getOrderCount(HttpServletRequest request){
        Integer  userId = usrService.getUserIdByPhone(request.getAttribute("userId").toString());
        //待支付订单数量
        Integer count1 = orderService.count(new QueryWrapper<JsProductOrder>().eq("usr_id",userId).eq("state",0));
        //待收货
        List<String> list2 = new ArrayList<>();
        list2.add("1");
        list2.add("2");
        Integer count2= orderService.count(new QueryWrapper<JsProductOrder>().eq("usr_id",userId).in("state",list2));
        //已完成数量
        List<String> list3 = new ArrayList<>();
        list3.add("3");
        list3.add("5");
        list3.add("6");
        list3.add("7");
        list3.add("99");
        Integer count3= orderService.count(new QueryWrapper<JsProductOrder>().eq("usr_id",userId).in("state",list3));
        //售后退款
        Integer count4 = orderService.count(new QueryWrapper<JsProductOrder>().eq("usr_id",userId).eq("state",4));
        List<Integer> list = new ArrayList<>();
        list.add(count1);
        list.add(count2);
        list.add(count3);
        list.add(count4);
        return R.ok().put("data",list);
    }

    /**
     * 市民云登录获取
     * @param code
     * @return
     */
    @UnAuthRequest
    @RequestMapping("/cityCloud")
    public R cityCloud(@RequestParam String code){
        //换取accessToken
        String url = "https://api.eshimin.com/api/oauth/token";
        Map map  = new HashMap<>();
        map.put("client_id","GEISr7PJPE");
        map.put("client_secret","aos6M25rvcTbQmtJD33nBsX9fkdvWscyHcQww8f0");
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("redirect_uri","https://www.laijinshanplay.cn/#/symlogin");
        String res = HttpUtil.get(url,map);
        if(StringUtils.isNotBlank(res)){
            JSONObject jsonObject = JSONUtil.parseObj(res);
            if(null!=jsonObject.get("access_token")&&null!=jsonObject.get("user")){
                String accessToken = jsonObject.get("access_token").toString();
                String userName = jsonObject.get("user").toString();
                String info = "https://api.eshimin.com/api/v2/user/identity/{userName}?access _token=xxx";
                String res4=info.replace("{userName}",userName).replace("xxx",accessToken);
                String result = HttpUtil.get(res4);
                if(StringUtils.isNotBlank(result)){
                    JSONObject jsonObject1 = JSONUtil.parseObj(result);
                    if(null!=jsonObject1.get("data")){
                        String data  = jsonObject1.get("data").toString();
                        JSONObject jsonObject2 = JSONUtil.parseObj(data);
                        if(null!=jsonObject2.get("mobile")&&null!=jsonObject2.get("name")){
                            String name = jsonObject2.get("name").toString();
                            String phone = jsonObject2.get("mobile").toString();
                            QueryWrapper<JsUsr> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("phone",phone);
                            JsUsr jsUsr = usrService.getOne(queryWrapper);
                            if(null==jsUsr){
                                JsUsr usr1 = new JsUsr();
                                usr1.setBalance(new BigDecimal("0"));
                                usr1.setNickname(name);
                                usr1.setPhone(phone);
                                usr1.setCreateDate(LocalDateTime.now());
                                usrService.save(usr1);
                            }
                            return R.ok().put("token",jwtUtils.generateToken(Long.valueOf(phone))).put("name",name);
                        }
                    }
                }
            }
        }
        return R.error();
    }


    @RequestMapping("/getPoints")
    public R getPoints(HttpServletRequest request){
        JsUsr usr = usrService.getOne(new QueryWrapper<JsUsr>().eq("phone",request.getAttribute("userId")));
        if(null!=usr){
            return R.ok().put("balance",usr.getBalance());
        }
        return R.error();
    }


}
